package com.runjian.rundo.iot.agent.iec104.parser.frame.control.process;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.StrUtil;
import com.runjian.rundo.iot.agent.iec104.consts.Ti;
import com.runjian.rundo.iot.agent.iec104.parser.frame.InfoElement;
import com.runjian.rundo.iot.agent.iec104.parser.frame.control.base.TaControl;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * C_CI_NA_1(0x65, "电能脉冲召唤命令")
 * 用于处理104协议中电能脉冲召唤的ASDU帧解析与组包
 *
 * @author YourName
 */
@Getter
@Setter
public class C_CI_NA_1 extends TaControl {

	private static final Logger log = LoggerFactory.getLogger(C_CI_NA_1.class);

	@Override
	public void init() {
		super.init();
		this.setTi(Ti.C_CI_NA_1);
		// 初始化一个信息元素
		InfoElement infoElement = InfoElement.<Void>builder().address(0).build();
		this.addInfoElement(infoElement);
	}

	@Override
	public void analysisInfo(byte[] msg) {
		int commonAddr = (msg[10] & 0xFF) | (msg[11] & 0xFF) << 8;
		//  解析可变结构限定词（索引7）
		int varStruct = msg[7] & 0xFF;
		// 存储解析后的信息元素
		this.addInfoElement(InfoElement.<Float>builder()
				.address(commonAddr)
				.build());

		this.setQos((short) varStruct);
	}

	/**
	 * 组包时写入信息体内容
	 *
	 * @param assembleByteBuf 字节缓存
	 * @param infoElement     信息元素（包含地址和脉冲值）
	 */
	@Override
	public void writeInfoContent(ByteBuf assembleByteBuf, InfoElement<Object> infoElement) {
		// 写入地址（3字节，截断int的低3字节）
		int address = (int) infoElement.getAddress();
		assembleByteBuf.writeBytes(new byte[]{
				(byte) (address >> 16),
				(byte) (address >> 8),
				(byte) address
		});

		// 写入脉冲值（4字节float）
		Object value = Optional.ofNullable(infoElement.getValue()).orElse(0);
		if (value instanceof Number) {
			float pulseValue = ((Number) value).floatValue();
			assembleByteBuf.writeBytes(ByteUtil.floatToBytes(pulseValue));
		} else if (value instanceof String) {
			float pulseValue = Float.parseFloat((String) value);
			assembleByteBuf.writeBytes(ByteUtil.floatToBytes(pulseValue));
		} else {
			log.error("不支持的脉冲值类型：{}", value.getClass().getSimpleName());
			assembleByteBuf.writeBytes(ByteUtil.floatToBytes(0F)); // 默认值
		}

		// 写入限定词（假设固定为0x01，根据协议调整）
		assembleByteBuf.writeByte(0x01);
	}
}